import {post} from "./Request";

export async function add(domain, param = {}) {
  const {data} = await post(`api/${domain}/add`, param);
  return data || false;
}

export async function update(domain, mu, param = {}) {
  const {data} = await post(`api/${domain}/update`, {mu, data: param});
  return data || false;
}

export async function one(domain, mu) {
  const {data} = await post(`api/${domain}/one`, {mu});
  return data || {};
}

export async function list(domain, param = {}) {
  const {data} = await post(`api/${domain}/list`, param);
  return data || [];
}

export async function page(domain, param = {}, pageNum = 1, pageSize = 15) {
  let {page: _page, mark} = await post(`api/${domain}/page`, {
    pageNum, pageSize, data: param,
  });

  if (_page) {
    let {list: _list = [], total = 0, current = 1} = _page;

    return {list: _list, total, current, mark};
  } else {
    return {
      list: [], total: 0, current: pageNum, mark,
    };
  }
}

export async function pages(domain, param = {}, pageNum = 1, pageSize = 15) {
  let {pages: _pages, mark} = await post(`api/${domain}/page`, {
    pageNum, pageSize, data: param,
  });

  if (_pages) {
    _pages.forEach((item) => {
      if (!item.list) {
        item = {list: [], total: 0, current: 1};
      }
    });
    return {pages: _pages, mark};
  } else {
    return {pages: {list: [], total: 0, current: pageNum}, mark};
  }
}

export async function search(uri, param = {}, pageNum = 1, pageSize = 15) {
  const {page: _page, mark} = await post(uri, {
    pageNum, pageSize, data: param,
  });
  let {list: _list = [], total = 0, current = 1} = _page;
  return {list: _list, total, current, mark};
}

export async function query(uri, param = {}) {
  const {data} = await post(uri, param);
  return data || {};
}

export async function submit(uri, param = {}) {
  const {data} = await post(uri, param);
  return data || {};
}

export function throttle(fn) {
  clearTimeout(fn.timeoutId);
  fn.timeoutId = setTimeout(function () {
    fn.call(null, {});
  }, 1000);
}
